import { AvatarDropdown, AvatarName, Footer } from '@/components';
import { currentUser as queryCurrentUser } from '@/services/api/user';
import { LinkOutlined } from '@ant-design/icons';
import type { Settings as LayoutSettings } from '@ant-design/pro-components';
import type { RunTimeLayoutConfig } from '@umijs/max';
import { history, Link } from '@umijs/max';
import defaultSettings from '../config/defaultSettings';
import logo from './../public/logo.png';
import { requestConfig } from './requestConfig';
const isDev = process.env.NODE_ENV === 'development';
const loginPath = '/user/login';

// 页面刷新时获取用户信息全局保存
export async function getInitialState() {
  const initialState: any = {
    currentUser: undefined,
    settings: defaultSettings as Partial<LayoutSettings>
  }
  // 如果不是登录页面，执行
  const { location } = history;
  if (location.pathname !== loginPath) {
    try {
      const res = await queryCurrentUser();
      initialState.currentUser = res.data
    } catch (error: any) {      
      // 如果未登录
      // history.push(loginPath);
    }
  }
  return initialState
}

// 定义无需进行身份验证的路径
const noAuthPaths = ['/user/login', '/user/register'];
// 在初始加载和路由切换时做一些事情。
export function onRouteChange({ location, routes, action }: any) {
  const { pathname } = location;
  // 从 localStorage 获取 token
  const token = localStorage.getItem('token');

  // 如果用户已经登录，并尝试访问登录页或注册页，则重定向到首页
  if (token && noAuthPaths.includes(pathname)) {
    history.push('/');
    return;
  }
  // 检查当前路径是否在无需验证的路径列表中
  if (!noAuthPaths.includes(pathname)) {
    // 如果 token 不存在，则跳转到登录页面
    if (!token) {
      history.push(`/user/login?redirect=${pathname}`);
    }
  }
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) => {
  return {
    logo,
    avatarProps: {
      src: initialState?.currentUser?.avatar_url || 'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png',
      title: <AvatarName />,
      render: (_, avatarChildren) => {
        return <AvatarDropdown>{avatarChildren}</AvatarDropdown>;
      },
    },
    // waterMarkProps: {
    //   content: initialState?.currentUser?.username,
    // },
    footerRender: () => <Footer />,
    onPageChange: () => {
      const { location } = history;
      // 如果没有登录，重定向到 login
      if (!initialState?.currentUser && location.pathname !== loginPath) {
        history.push(loginPath);
      }
    },
    links: isDev
      ? [
          <Link key="openapi" to="/umi/plugin/openapi" target="_blank">
            <LinkOutlined />
            <span>OpenAPI 文档</span>
          </Link>,
        ]
      : [],
    menuHeaderRender: undefined,
    // 自定义 403 页面
    unAccessible: <div>unAccessible</div>,
    ...initialState?.settings,
  };
};

/**
 * @name request 配置，可以配置错误处理
 * 它基于 axios 和 ahooks 的 useRequest 提供了一套统一的网络请求和错误处理方案。
 * @doc https://umijs.org/docs/max/request#配置
 */
export const request = requestConfig;
